import Vue from 'vue'
import VueRouter from 'vue-router'
// 引入组件
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'
import Users from '../components/user/Users.vue'
import Rights from '../components/authority/Rights.vue'
import Roles from '../components/authority/Roles.vue'
import Cate from '../components/goods/Cate.vue'
import Params from '../components/goods/Params.vue'
import List from '../components/goods/List.vue'
import Add from '../components/goods/Add.vue'
import Order from '../components/order/Order.vue'
import Reports from '../components/reports/Reports.vue'
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login },
    {
      path: '/home',
      component: Home,
      redirect: '/users',
      children: [
        { path: '/users', component: Users },
        { path: '/rights', component: Rights },
        { path: '/roles', component: Roles },
        { path: '/categories', component: Cate },
        { path: '/params', component: Params },
        { path: '/goods', component: List },
        {path: '/goods/add', component: Add},
        {path: '/orders', component: Order},
        {path: '/reports', component: Reports}
      ]
    }
  ]
})
// 为路由对象，添加前置守卫
router.beforeEach((to, from, next) => {
  // 如果用户访问的登录页，直接放行
  if (to.path === '/login') return next()
  // 从sessionstorage获取到的值
  const token = window.sessionStorage.getItem('token')
  // 没有token的值，强制跳转到登录页面
  if (!token) return next('/login')
  next()
})

export default router
